
# R 4.0.4
library(dplyr) # version 1.0.5
library(readstata13) # v 0.10.0
library(foreign) # v 0.8-81

# Comparative Candidate Survey data is available here:
# https://forsbase.unil.ch/project/study-public-overview/17220/0/
  
d <- read.dta13(file="Data/CCS/620_CCS_Data_Wave1_v3.1.dta")

d <- d[d$t1 == "Ireland" & d$a1 < 7 & !is.na(d$a1),] # remove independents (7) 

table(d$b7)
d$ivsp <- recode(d$b7,  `0` = 10, `.1` = 9, `.2` = 8,  `.3` = 7,  `.4` = 6, `.5` = 5,  `.6` = 4,
                 `.7` = 3,  `.8` = 2,  `.9` = 1,  `1` = 0)
# in the new variable, 10 is the most individual/candidate-focused value
table(d$ivsp)
table(d$ivsp, d$b7)
d$ivsp01 <- as.numeric(d$ivsp > 5,1, 0)

tmp <- data.frame(a1=1:6,
                  party=c("FF","FG","Greens","Labour","PD","SF"), stringsAsFactors = F)
d <- merge(d,tmp)

d$ff <- as.numeric(d$party == "FF", 1, 0)


d$councillor <- as.numeric(d$a9e >0, 1, 0) # years as member of local assembly
d$townsize <- d$e4

d$percmarg <- NA
d$percmarg[!is.na(d$b16) & (d$b16 == "I thought I could hardly lose" |  d$b16 == "I thought I could not lose")] <- 1
d$percmarg[!is.na(d$b16) & (d$b16 == "I thought it was an open race")] <- 2
d$percmarg[!is.na(d$b16) & (d$b16 == "I thought I could not win" |  d$b16 == "I thought I could hardly win")] <- 3
table(d$percmarg, useNA="ifany")
d$percmarg <- factor(d$percmarg)
levels(d$percmarg) <- c("safe","open","difficult")

# code running mate 0/1 
d$nomate <- ifelse(d$party=="FG" &  !is.na(d$t6) &
                     d$t6 %in% c(9,10,11,12,13,14,15,18,19,20,24,37,38), 1, 0)
d$nomate[d$party=="FG" & is.na(d$t6)] <- NA
d$nomate[d$party=="FF"] <- 0 # always at least two cand 
d$nomate[d$party!="FF" & d$party != "FG"] <- NA
d$rmate <- 1-d$nomate

d$female <- as.numeric(d$e1 == "female", 1, 0)


dstata <- d[d$party %in% c("FF","FG"), c("party","ff","ivsp","ivsp01","female",
                                         "councillor","townsize","percmarg","rmate","t6")]
write.dta(dstata, file="CCS_replication.dta")
